import 'package:dio/dio.dart' as dio;
import 'package:flutter_archer/routes/routes.dart';
import 'package:flutter_archer/shared/constants/common.dart';
import 'package:flutter_archer/shared/services/persistent/persistent.dart';
import 'package:flutter_archer/ui/auth/auth_controller.dart';
import 'package:get/get.dart';

class AuthInterceptor extends dio.Interceptor {

  @override
  void onRequest(dio.RequestOptions options, dio.RequestInterceptorHandler handler) async{
    SpPersistentor sp = Get.find();
    String? accessToken = await sp.getStorage(CommonConstants.KEY_TOKEN);
    if (accessToken != null && accessToken != '') {
      options.headers['x-token'] = accessToken;
    }
    return super.onRequest(options, handler);
  }

  @override
  void onResponse(dio.Response response, dio.ResponseInterceptorHandler handler) {
    return super.onResponse(response, handler);
  }

  @override
  void onError(dio.DioError err, dio.ErrorInterceptorHandler handler) {
    if(err.type == dio.DioErrorType.response && err.response?.statusCode == 401){
      AuthController controller = Get.find();
      Get.toNamed(Routes.AUTH + Routes.LOGIN, arguments: controller);
    }
    return super.onError(err, handler);
  }
}